import axios from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.NODE_ENV == 'development' ?  '/rs' : '',
  timeout: 5000
});

service.interceptors.request.use(config => {
  config.headers['Content-Key'] = "a35a1281e2cb8e6c519a8f4943ba8f9b";
  config.headers['X-Requested-With'] = "XMLHttpRequest";

  if (config.method == 'get') {
    config.params = {
      _t: Date.now(),
      ...config.params
    }
  }

  return config;
}, error => {
  return Promise.reject(error);
});


service.interceptors.response.use(response => {

  if (response.status == 200 && response.data && response.data.code == 0) {
    return response.data.data;
  } else if (response.data && response.data.code == -3) {
    Message({
      message: "登陆超时",
      type: 'error',
      duration: 5000
    });
    window.location.href = '/login.html';
    return Promise.reject(response.data);

  } else {
    return Promise.reject(response.data);
  }

}, error => {
  Message({
    message: error.message || '系统异常',
    type: 'error',
    duration: 5000
  });
  return Promise.reject(error);
});


export default service;
